/**	
 * Author : Mht
 * Desc : For 2016 RDM 
 */
package servlet.menu;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import common.SignUtil;
import lombok.extern.log4j.Log4j;
import service.message.MessageProcessService;

/**
 * @author Mht
 * @date May 31, 2016
 */
@SuppressWarnings("serial")
@Log4j
public class MenuCoreServlet extends HttpServlet {

	private Map<String, String> map = new HashMap<String, String>();

	public MenuCoreServlet() {
		map.put(MessageProcessService.class.getSimpleName(), "coreService");
		log.info("[Initialize Menu Core Servlet]");
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		String IP = request.getRemoteAddr();
		PrintWriter out = response.getWriter();

		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			log.info(String.format("Check Signature [ip=%s,signature=%s,timestamp=%s,nonce=%s] Successfully", IP,
					signature, timestamp, nonce));
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");

		// 利用Servlet上下文找到所注解的Bean实例
		MessageProcessService coreService = (MessageProcessService) findInjectBean(
				MessageProcessService.class.getSimpleName());

		// 调用核心处理服务处理请求
		String respMessage = coreService.processRequest(req);

		// 响应消息
		PrintWriter out = resp.getWriter();
		out.print(respMessage);
		out.close();
	}

	private Object findInjectBean(String beanName) {
		ServletContext servletContext = this.getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		return (Object) wac.getBean(map.get(beanName));
	}
}
